package com.light.gulimall.product.service.impl;

import com.light.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.light.gulimall.product.dao.AttrDao;
import com.light.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.light.gulimall.product.entity.AttrEntity;
import com.light.gulimall.product.vo.AttrGroupVO;
import com.light.gulimall.product.vo.AttrVO;
import com.light.gulimall.product.vo.WithAttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;

import com.light.gulimall.product.dao.AttrGroupDao;
import com.light.gulimall.product.entity.AttrGroupEntity;
import com.light.gulimall.product.service.AttrGroupService;
import org.springframework.util.CollectionUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据前端传递的参数和catelogId查询
     *
     * @param params    前端传递参数
     * @param catelogId 分类id
     * @return 分页查询结果集
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        //如果catelogId == 0 查询全量
        PageUtils pageUtils = null;
        if (catelogId == 0) {
            pageUtils = this.queryPage(params);
        } else {
            //根据条件分页查询
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId);
            //查询条件
            String key = ((String) params.get("key"));
            if (!StringUtils.isBlank(key)) {
                wrapper.and((obj) -> {
                    obj.eq("attr_group_id", key).or().like("attr_group_name", key);
                });
            }
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            pageUtils = new PageUtils(page);
        }
        return pageUtils;
    }

    /**
     * 根据分类id查询信息
     *
     * @param attrGroupId 分类id
     * @return 查询到的结果集
     */
    @Override
    public AttrGroupVO getInfoById(Long attrGroupId) {
        AttrGroupEntity attrGroup = this.getById(attrGroupId);
        //向上找父级id
        Long groupId = attrGroup.getCatelogId();
        List<AttrGroupEntity> parentCategories = attrGroupDao.findParentCategories(groupId);

        AttrGroupVO vo = new AttrGroupVO();
        BeanUtils.copyProperties(attrGroup, vo);
        // 筛选出 catelogId 并转换为 Long 类型的 List，并按升序排序
        List<Long> catelogIdList = parentCategories.stream()
                .map(AttrGroupEntity::getCatelogId)
                .sorted()
                .collect(Collectors.toList());
        vo.setCatelogIds(catelogIdList);
        return vo;
    }


    /**
     * 获取指定分组关联的所有属性
     *
     * @param attrgroupId pms_attr_group 属性分组表 主键id
     * @return 查询结果
     */
    @Override
    public List<AttrEntity> getRelation(Long attrgroupId) {
        //根据attrgroupId 查询pms_attr_attrgroup_relation 表
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_group_id", attrgroupId);
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(wrapper);
        ArrayList<AttrVO> attrVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(relationEntities)) {
            List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            //根据attrIds查询pms_attr表
            return attrDao.selectBatchIds(attrIds);
        }
        return null;
    }

    /**
     * 获取分类下所有分组&关联属性
     *
     * @param catelogId 所属分类id
     * @return 查询结果集
     */
    @Override
    public List<WithAttrVO> getWithAttr(Long catelogId) {
        ArrayList<WithAttrVO> withAttrVOS = new ArrayList<>();


        //根据catelogId 所属分类id查询pms_attr_group
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
        attrGroupEntityQueryWrapper.eq("catelog_id", catelogId);
        List<AttrGroupEntity> list = list(attrGroupEntityQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<Long> attrIds = null;
        //根据pms_attr_group 查询到结果集的attr_group_id 查询pms_attr_attrgroup_relation的attr_id
        for (AttrGroupEntity attrGroupEntity : list) {
            WithAttrVO vo = new WithAttrVO();
            BeanUtils.copyProperties(attrGroupEntity, vo);
            Long attrGroupId = attrGroupEntity.getAttrGroupId();
            QueryWrapper<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntityQueryWrapper = new QueryWrapper<>();
            attrAttrgroupRelationEntityQueryWrapper.eq("attr_group_id", attrGroupId);
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(attrAttrgroupRelationEntityQueryWrapper);
            if (!CollectionUtils.isEmpty(attrAttrgroupRelationEntities)) {
                attrIds = attrAttrgroupRelationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(attrIds)) {
                QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
                attrEntityQueryWrapper.in("attr_id", attrIds);
                List<AttrEntity> attrEntities = attrDao.selectList(attrEntityQueryWrapper);
                if (!CollectionUtils.isEmpty(attrEntities)) {
                    vo.setAttrs(attrEntities);
                }
            }
            withAttrVOS.add(vo);
        }

        return withAttrVOS;
    }

}